package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {


    private Socket socket;
    private Map<String, Context> contextMap;
    public RequestProcessor(Socket socket, Map<String, Context> contextMap) {
        this.socket = socket;
        this.contextMap = contextMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            String url = request.getUrl();

            // 判断属于哪个context 需要解读所有context
            Context currentContext = null;
            for (String project : contextMap.keySet()) {
                String prifex = "/" + project;
                if (url.startsWith(prifex)) {
                    // 获取匹配的context
                    url = url.replace(prifex, "");
                    currentContext = contextMap.get(project);
                    break;
                }
            }
            // 没有项目输出404
            if (currentContext == null) {
                response.outputHtml(request.getUrl());
                return;
            }

            Map<String, HttpServlet> servletMap = currentContext.getServletMap();
            // 主页
            if ("/".equals(url)) {
                response.outputHtml(currentContext.getPrefix() + "/index.html");
            }
            // 静态资源处理
            if(servletMap.get(url) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(url);
                System.out.println(httpServlet);
                httpServlet.service(request,response);
            }

        }catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
